package com.summer.shopping.controller;

import com.summer.shopping.domain.common.req.ReqHolder;
import com.summer.shopping.domain.table.Address;
import com.summer.shopping.domain.table.dto.AddressDTO;
import com.summer.shopping.domain.table.dto.PageDTO;

import com.summer.shopping.service.AddressService;
import com.summer.shopping.utils.PageResult;
import com.summer.shopping.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;


    // 分页查询地址
    @PostMapping("/page")
    public Result pageAddress(@RequestBody PageDTO pageDTO) {
        PageResult<Address> result = addressService.pageQuery(pageDTO);
        return Result.ok(result);
    }
    // 创建地址
    @PostMapping
    public Result createAddress(@RequestBody AddressDTO dto) {
        Address address = new Address();
        address.setName(dto.getName());
        address.setArea(dto.getArea());
        address.setPhone(dto.getPhone());
        address.setOtherName(dto.getOtherName());
        address.setIsDefault(dto.getIsDefault());
        Long userId = ReqHolder.getUserId();
        address.setUserId(userId);
        boolean saved = addressService.save(address);
        return saved ? Result.ok("地址创建成功") : Result.error("地址创建失败");
    }

    // 更新地址
    @PutMapping("/{id}")
    public Result updateAddress(@PathVariable Integer id, @RequestBody AddressDTO dto) {
        Address address = new Address();
        address.setId(id);
        address.setName(dto.getName());
        address.setArea(dto.getArea());
        address.setPhone(dto.getPhone());
        address.setOtherName(dto.getOtherName());
        address.setIsDefault(dto.getIsDefault());
        boolean updated = addressService.updateById(address);
        return updated ? Result.ok("地址更新成功") : Result.error("地址更新失败");
    }

    // 删除地址
    @DeleteMapping("/{id}")
    public Result deleteAddress(@PathVariable Integer id) {
        boolean removed = addressService.removeById(id);
        return removed ? Result.ok("地址删除成功") : Result.error("地址删除失败");
    }

    // 获取地址详情
    @GetMapping("/{id}")
    public Result getAddress(@PathVariable Integer id) {
        Address address = addressService.getById(id);
        return address != null ? Result.ok(address) : Result.error("地址不存在");
    }




}
